<?php

namespace App\ApiBackend\Admin;

use App\Http\Controllers\ApiBaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


/**
 *  用户列表
 */
class Page extends ApiBaseController
{
  private array $searchMap = [
    "username" => ["su.username", "="],
    "name" => ["su.name", "like"],
    "status" => ["su.status", "="],
    "deptId" => ["ad.id", "="],
  ];

  /**
   * 参数检查
   */
  protected function check(): void
  {
  }

  /**
   * 业务主体
   */
  protected function service(): void
  {
    //基础查询构造器
    $selectFields = [
      "aa.*",
      "ad.deptName",
      "ad.id as deptId",
      "ar.roleName",
      "ar.id as roleId",
    ];
    $queryConstructor = DB::table('admin as aa')
      ->join('admin_department as ad', 'ad.id', '=', 'aa.adminDepartmentId')
      ->leftJoin('admin_role as ar', 'ar.id', '=', 'aa.adminRoleId')
      ->select($selectFields)
      ->where('aa.username', '!=', 'liwei')
      ->orderBy("aa.adminId", "ASC");

    //搜索条件
    $this->querySearchConstructor($queryConstructor, $this->searchMap);

    //是否需要分页
    $isPage = strpos(request()->path(), "page") ? 1 : 0;
    if ($isPage) {// 分页查询
      $total = $queryConstructor->count();
      $pageNumber = \request("pageNum", 1);
      $pageSize = \request("pageSize", 20);
      $queryConstructor->offset(($pageNumber - 1) * $pageSize)->limit($pageSize);
    }

    $listData = $queryConstructor->get();
    empty($listData) && $listData = [];

    //返回结果
    if ($isPage) {// 分页查询
      $this->result["data"]["list"] = $listData;
      $this->result["data"]["total"] = $total;
    } else {
      $this->result["data"]["list"] = $listData;
    }
  }
}
